/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jtwitt.client.gui;

import java.io.IOException;
import jtwitt.socket.ClientThread;
import jtwitt.util.Actions;

/**
 * User Login form 
 * 
 * @author Maria
 */
public class Login extends javax.swing.JFrame {

    ClientThread cThread;
    MainClient gui;

    public String username;
    public String password;
    public int connected;
 
      /**
     * Creates a new Login form 
     * @param cThread ClientThread 
     */
    public Login() {
        
            initComponents();
            
            this.setTitle("Login");
                                             
            jErrorLabel.setVisible(false);
            //checkConnection();
           
        
    }


    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel3 = new javax.swing.JLabel();
        jUsername = new javax.swing.JTextField();
        Ok = new javax.swing.JButton();
        Clear = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jPassword = new javax.swing.JPasswordField();
        jErrorLabel = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jTextServerIP = new javax.swing.JTextField();
        jTextPort = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jButtonRegister = new javax.swing.JButton();

        jLabel3.setText("jLabel3");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        Ok.setText("OK");
        Ok.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                OkActionPerformed(evt);
            }
        });

        Clear.setText("CLEAR");
        Clear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ClearActionPerformed(evt);
            }
        });

        jLabel1.setText("Enter username or email:");

        jLabel2.setText("Enter password:");

        jErrorLabel.setForeground(new java.awt.Color(255, 0, 0));
        jErrorLabel.setText("Incorrect username and/or password, please try again.");

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel5.setText("    Please enter the following to access jTwitt:");

        jTextServerIP.setText("localhost");

        jTextPort.setText("1234");

        jLabel4.setText("Enter Server IP:");

        jLabel6.setText("Enter Port:");

        jButtonRegister.setText("Register");
        jButtonRegister.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonRegisterActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap(45, Short.MAX_VALUE)
                        .addComponent(jErrorLabel))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(54, 54, 54)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel1)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel6, javax.swing.GroupLayout.Alignment.TRAILING)))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jUsername)
                            .addComponent(jPassword)
                            .addComponent(jTextServerIP)
                            .addComponent(jTextPort))))
                .addGap(65, 65, 65))
            .addGroup(layout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 289, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(89, 89, 89)
                .addComponent(Ok, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(Clear, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButtonRegister)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(29, 29, 29)
                .addComponent(jLabel5)
                .addGap(39, 39, 39)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextServerIP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 34, Short.MAX_VALUE)
                .addComponent(jErrorLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Ok)
                    .addComponent(Clear)
                    .addComponent(jButtonRegister))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void OkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OkActionPerformed
     
        //if no null fields
        if("".equals(jUsername.getText()) || "".equals(jPassword.getText()) || "".equals(jTextServerIP.getText()) || "".equals(jTextPort.getText())){
            
                jErrorLabel.setText("Not enough info, please fill the blanks.");
                jErrorLabel.setVisible(true);
        }
        
        else{

                lockControls();
  
                username=jUsername.getText();
                password=jPassword.getText();
     

                try{
                
//                if(connected !=4)//if no connection
//                {
                //connect to the server
                connected=gui.startThreads(jTextServerIP.getText(),Integer.parseInt(jTextPort.getText()));
                    
                if(connected == 2){
                             jErrorLabel.setText("Don't know about host: hostname "+jTextServerIP.getText()+" on port:"+jTextPort.getText());

                            unlockControls();
                              
                            jTextServerIP.setEnabled(true);
                            jTextPort.setEnabled(true);
                    }
                else if(connected == 3){
                             jErrorLabel.setText("Couldn't get I/O for the connection to: hostname"+jTextServerIP.getText()+" on port:"+jTextPort.getText());

                            unlockControls();
                              
                            jTextServerIP.setEnabled(true);
                            jTextPort.setEnabled(true);
                    }
               
                   
                else if (connected == 4) {//if connected , user cannot change connection parameters
                            jErrorLabel.setText("Connected to server: "+jTextServerIP.getText()+" on port:"+jTextPort.getText());
                            jErrorLabel.setVisible(true);
                                                    
                            jTextServerIP.setEnabled(false);
                            jTextPort.setEnabled(false);
                    }
                     
                cThread = gui.getCThread();
                //gui.setCThread(cThread);
     
                cThread.setLogin(this);
     
                cThread.setAction(Actions.LOGIN);
                cThread.wakeMe();
    
                }catch(NumberFormatException | IOException ex){
                            jErrorLabel.setText("Problem connecting to server: "+ex);
                            jErrorLabel.setVisible(true);
                            unlockControls();
                }
            }
        
    }//GEN-LAST:event_OkActionPerformed

    private void ClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ClearActionPerformed
        
        jUsername.setText("");
        jPassword.setText("");
        jTextServerIP.setText("localhost");
        jTextPort.setText("1234");
        jErrorLabel.setVisible(false);

    }//GEN-LAST:event_ClearActionPerformed

    private void jButtonRegisterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRegisterActionPerformed
     
        Register register = new Register(this,true);
        register.setMainClient(gui);
        register.setVisible(true);
        //this.setVisible(false);
        
        
    }//GEN-LAST:event_jButtonRegisterActionPerformed

//    /**
//     * @param args the command line arguments
//     */
//    public static void main(String args[]) {
//        /* Set the Nimbus look and feel */
//        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
//        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
//         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
//         */
//        try {
//            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
//                if ("Nimbus".equals(info.getName())) {
//                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
//                    break;
//                }
//            }
//        } catch (ClassNotFoundException ex) {
//            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (InstantiationException ex) {
//            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (IllegalAccessException ex) {
//            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
//            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        }
//        //</editor-fold>
//
//        /* Create and display the form */
//        java.awt.EventQueue.invokeLater(new Runnable() {
//            @Override
//            public void run() {
//                new Login().setVisible(true);
//            }
//        });
//        
//    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Clear;
    private javax.swing.JButton Ok;
    private javax.swing.JButton jButtonRegister;
    private javax.swing.JLabel jErrorLabel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPasswordField jPassword;
    private javax.swing.JTextField jTextPort;
    private javax.swing.JTextField jTextServerIP;
    private javax.swing.JTextField jUsername;
    // End of variables declaration//GEN-END:variables

    /**
     * Gets the userId if the username and password match, sets
     * login invisible, the main client visible and result as the userId in main client.
     * Else it displays an error message through jErrorLabel
     * @param result
     */
    public void getLoginResult(int result){

        if(result>0){

               gui.user=result;
               gui.setVisible(true);
               
               this.dispose();
       }
        else{
                jErrorLabel.setText("Incorrect username and /or password, please try again");
                unlockControls();
        }
}
    /**
     * Disable controls until actions performed
     */
    
    public void lockControls(){

            jUsername.setEnabled(false);
            jPassword.setEnabled(false);
            jTextServerIP.setEnabled(false);
            jTextPort.setEnabled(false);
            jErrorLabel.setVisible(false);
            Ok.setEnabled(false);
            Clear.setEnabled(false);
            jButtonRegister.setEnabled(false);
            repaint();
   } 
    /**
     * Re-enable controls after actions performed
     */
    public void unlockControls(){
        
            jUsername.setEnabled(true);
            jPassword.setEnabled(true);
            jErrorLabel.setVisible(true);
            Ok.setEnabled(true);
            Clear.setEnabled(true);
            jButtonRegister.setEnabled(true);
            repaint();
   }

    public void setMainClient(MainClient gui) {
        this.gui = gui;
    }

//    private void checkConnection() {
//        if(gui.getCThread()!=null)
//        {
//            jTextServerIP.setEnabled(false);
//            jTextPort.setEnabled(false);
//            
//        }
//            
//    }

}
